package org.icdio.servlet;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.icdio.entity.*;
import org.icdio.service.RegisterService;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class register
 */
@WebServlet("/register")
public class register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		doPost(request, response);
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String repassword = request.getParameter("repassword");
		
		RegisterService registerService = new RegisterService();
		JSONObject jsonObject = new JSONObject();
		
		if(password.equals(repassword)) {
			User user = new User();
			user.setUserName(userName);
			user.setPassword(password);
			try {
				if(registerService.register(user)) {
					jsonObject.put("message", "注册成功！");
				}else {
					jsonObject.put("message", "注册失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	
		}else {
			jsonObject.put("message", "两次输入的密码不同！");
		}
		
		System.out.println(jsonObject.toString());
		response.getWriter().write(jsonObject.toString());
	}

}
